const express = require('express');
const router = express.Router();
const auth = require('../middleware/auth');
const Course = require('../models/course');
const Class = require('../models/class');

// 获取课程列表
router.get('/', auth, async (req, res) => {
  try {
    const { week } = req.query;
    const userId = req.user.id;
    const userRole = req.user.role;

    let courses;
    if (userRole === 'teacher') {
      // 获取教师创建的课程
      courses = await Course.findAll({
        where: {
          teacherId: userId,
          startWeek: { [Op.lte]: week },
          endWeek: { [Op.gte]: week }
        },
        include: [{
          model: Class,
          attributes: ['name']
        }]
      });
    } else {
      // 获取学生所在班级的课程
      const studentClass = await Class.findOne({
        where: { id: req.user.classId }
      });
      
      courses = await Course.findAll({
        where: {
          classId: studentClass.id,
          startWeek: { [Op.lte]: week },
          endWeek: { [Op.gte]: week }
        },
        include: [{
          model: Class,
          attributes: ['name']
        }]
      });
    }

    res.json({
      success: true,
      courses: courses.map(course => ({
        id: course.id,
        name: course.name,
        location: course.location,
        dayIndex: course.dayIndex,
        timeIndex: course.timeIndex,
        className: course.Class.name
      }))
    });

  } catch (error) {
    console.error('Get courses error:', error);
    res.status(500).json({
      success: false,
      message: error.message
    });
  }
});

// 添加课程
router.post('/', auth, async (req, res) => {
  try {
    if (req.user.role !== 'teacher') {
      return res.status(403).json({
        success: false,
        message: '只有教师可以添加课程'
      });
    }

    const {
      name,
      location,
      classId,
      dayIndex,
      timeIndex,
      startWeek,
      endWeek
    } = req.body;

    // 检查时间冲突
    const conflictCourse = await Course.findOne({
      where: {
        classId,
        dayIndex,
        timeIndex,
        [Op.or]: [
          {
            startWeek: { [Op.between]: [startWeek, endWeek] }
          },
          {
            endWeek: { [Op.between]: [startWeek, endWeek] }
          }
        ]
      }
    });

    if (conflictCourse) {
      return res.status(400).json({
        success: false,
        message: '该时间段已有课程'
      });
    }

    const course = await Course.create({
      name,
      location,
      classId,
      teacherId: req.user.id,
      dayIndex,
      timeIndex,
      startWeek,
      endWeek
    });

    res.json({
      success: true,
      course
    });

  } catch (error) {
    console.error('Add course error:', error);
    res.status(500).json({
      success: false,
      message: error.message
    });
  }
});

module.exports = router;